package com.linkhub.oms.admin.common.aspect;

import com.alibaba.fastjson.JSON;
import com.linkhub.oms.common.util.QtObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: WebLogAspect
 * @Author: echo
 * @Date: 2024/3/3 13:44
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class WebLogAspect {


    /**
     * 以 controller 包下定义的所有请求为切入点
     */
    @Pointcut("execution(public * com.linkhub.oms.admin.modules.*.controller.*.*(..)) || " +
            "execution(public * com.linkhub.oms.admin.modules.*.*.controller.*.*(..))")
    public void webAop() {
        // empty
    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("webAop()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        List<Object> logArgs = Arrays.stream(proceedingJoinPoint.getArgs())
                .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse) && !(QtObjectUtil.isMultiPartFile(arg))))
                .collect(Collectors.toList());
        //请求参数
        String requestJSONStr = JSON.toJSONString(logArgs);
        //请求日志
        beforeLog(request, requestJSONStr);

        //请求结果
        Object result = proceedingJoinPoint.proceed();
        //返回日志
        afterLog(startTime, result);

        return result;
    }

    private void beforeLog(HttpServletRequest request, String requestJSONStr) {
        if (log.isInfoEnabled()) {
            log.info("=== WebLogAspect Start ===");
            // 打印请求 url
            log.info("Request URL: {}", request.getRequestURL().toString());
            // 打印请求的 IP
            log.info("Request IP: {}", request.getRemoteAddr());
            // 打印请求入参
            log.info("Request Args: {}", requestJSONStr);
        }
    }

    private void afterLog(long startTime, Object result) {
        // 打印出参
        if (log.isInfoEnabled()) {
            log.debug("Response Args: {}", JSON.toJSONString(result));
            // 执行耗时
            log.info("Response Time: {} ms", System.currentTimeMillis() - startTime);
            log.info("=== WebLogAspect End ===");
        }
    }


}
